<?php

App::uses('AppController', 'Controller');

/**
 * Companies Controller
 *
 * @property Company $Company
 */
class CompaniesController extends AppController {

  function beforeFilter() {
//    $this->Auth->allow('index');
    $this->set('title_for_layout', 'Transportes');
  }

  /**
   * index method
   *
   * @return void
   */
  public function index() {
    $this->Company->recursive = 0;
    $this->paginate = array('limit' => 1000);
    $this->set('companies', $this->paginate());
    $this->set('title_for_layout', 'Transporte Villa');
  }

  public function search() {
    $name = '%' . trim($this->request->data('name')) . '%';
    $this->paginate = array(
        'conditions' => array('Company.social_razon LIKE' => $name));
    $this->set('companies', $this->paginate());
    $this->layout = 'ajax';
  }

  /**
   * index method
   *
   * @return void
   */
  public function xls() {

    $this->set('title_for_layout', 'Gestor de Archivos');

    if (!empty($this->data) && is_uploaded_file($this->data['File']['tmp_name'])) {

      $this->set('file', file($this->data['File']['tmp_name']));

      $basename = 'PER_modified' . date("d-m-Y");
      $name = $basename . '.txt';
//
      $ar = fopen("files/results/" . $name, "a") or die("Problemas en la creacion");

      $filas = file($this->data['File']['tmp_name']);

//// iniciamos contador y la fila a cero
      $i = 0;
      $numero_fila = 0;
      $row = $filas[0];

// mientras exista una fila

      while ($filas[$i] != NULL) {

//// incremento contador de la fila
        $row2 = trim($row);
        $size = strlen(($row2)) - 1;
        $columna = $size - (15);
//
        $lugar = $columna;
        $cadena = $row2;
        $insertar = '0';
        $resultado = substr($row2, 0, $lugar) . $insertar . substr($cadena, $lugar);
//
        fputs($ar, utf8_decode($resultado) . chr(13) . chr(10)); //para dar un salto de linea en txt es con las siglas. chr(13).chr(10)
//
//// incrementamos contador
        $i++;
        $numero_fila++;
        $row = $filas[$i];
      }

      fclose($ar);


      chmod('files/results/' . $name, 0777);
      $this->Session->setFlash(__('Los datos se cargaron correctamente'));

      $this->set('archivo', $basename);
    }
  }

  public function download($file = null) {

    $this->viewClass = 'Media';
//    Render app/webroot/files/example.docx
    $params = array(
        'id' => $file . '.txt',
        'name' => $file,
        'extension' => 'txt',
        'download' => true,
//        'mimeType' => array(
//            'csv' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
//        ),
        'path' => 'files/results' . DS
    );
    $this->set($params);
  }

  /**
   * ajax index method
   *
   * @return void
   */
  public function indexAjax() {
    $this->Company->recursive = 0;
    $this->set('companies', $this->paginate());
    $this->set('title_for_layout', 'Transporte Villa');
    $this->layout = 'ajax';
  }

  /**
   * view method
   *
   * @throws NotFoundException
   * @param string $id
   * @return void
   */
  public function view($id = null) {
    if (!$this->Company->exists($id)) {
      throw new NotFoundException(__('Invalid company'));
    }
    $options = array('conditions' => array('Company.' . $this->Company->primaryKey => $id));
    $this->set('company', $this->Company->find('first', $options));
  }

  /**
   * Ajax add method
   *
   * @return void
   */
  public function addAjax() {
    if ($this->request->is('post')) {
      $this->Company->create();
      if ($this->Company->save($this->request->data)) {
        $this->Session->setFlash(__('La Empresa ha sido Guardada exitosamente'));
        $this->redirect('/');
      } else {
        $this->Session->setFlash(__('La Empresa no ha sido Guardada'));
      }
    }
    $this->layout = 'ajax';
  }

  /**
   * add method
   *
   * @return void
   */
  public function add() {
    if ($this->request->is('post')) {
      $this->Company->create();
      if ($this->Company->save($this->request->data)) {
        $this->Session->setFlash(__('La Empresa ha sido Guardada exitosamente'));
        $this->redirect('/');
      } else {
        $this->Session->setFlash(__('La Empresa no ha sido Guardada. Intente Nuevamente'));
      }
    }
  }

  /**
   * edit method
   *
   * @throws NotFoundException
   * @param string $id
   * @return void
   */
  public function edit($id = null) {

    $this->Company->id = $id;


    if (!$this->Company->exists($id)) {
      throw new NotFoundException(__('Invalid company'));
    }
    if ($this->request->is('post') || $this->request->is('put')) {
      if ($this->Company->save($this->request->data)) {
        $this->Session->setFlash(__('La Empresa ha sido Guardada exitosamente'));
        $this->redirect(array('action' => 'index'));
      } else {
        $this->Session->setFlash(__('La Empresa no ha sido Guardada. Intente Nuevamente'));
      }
    } else {
      $options = array('conditions' => array('Company.' . $this->Company->primaryKey => $id));
      $this->request->data = $this->Company->find('first', $options);
    }
  }

  /**
   * delete method
   *
   * @throws NotFoundException
   * @throws MethodNotAllowedException
   * @param string $id
   * @return void
   */
  public function delete($id = null) {
    $this->Company->id = $id;
    if (!$this->Company->exists()) {
      throw new NotFoundException(__('Invalid company'));
    }
    $this->request->onlyAllow('post', 'delete');
    if ($this->Company->delete()) {
      $this->Session->setFlash(__('Empresa Borrada'));
      $this->redirect(array('action' => 'index'));
    }
    $this->Session->setFlash(__('Empresa no Borrada'));
    $this->redirect(array('action' => 'index'));
  }

}
